package response

import (
	"fmt"
	"net/http"
	"reflect"

	"github.com/gin-gonic/gin"
)

const (
	SUCCESS = 200
	ERROR   = 400
)

type Data struct {
	context *gin.Context
	message string
	data    interface{}
	total   int64
}

func Response(c *gin.Context) *Data {
	return &Data{
		context: c,
		message: "操作成功",
		total:   -1,
	}
}

func (d *Data) Message(value string) *Data {
	d.message = value
	return d
}

func (d *Data) base(data gin.H) {
	d.context.JSON(http.StatusOK, data)
}

func (d *Data) Data(data interface{}) *Data {
	d.data = data
	return d
}

func (d *Data) Count(num int64) *Data {
	d.total = num
	return d
}

func (d *Data) Success() {
	data := map[string]interface{}{
		"code": 200,
		"msg":  d.message,
		"data": d.data,
	}

	if d.total >= 0 {
		data["total"] = d.total
	}

	d.base(data)
}

func (d *Data) Error() {
	var a map[string]interface{} = map[string]interface{}{
		"code": 400,
		"msg":  d.message,
		//"data": d.data,
	}
	d.base(a)
}

func (d *Data) Bind(bind map[string]string) *Data {
	elem := reflect.ValueOf(d.data)
	switch elem.Kind().String() {
	case "slice":
		// for _, v := range d.data.([]interface{}) {
		// 	e := reflect.ValueOf(v)
		// 	for k1 := range bind {
		// 		fmt.Println(e.FieldByName(k1))
		// 	}
		// }
	default:
		fmt.Println(1)
	}

	return d
}

func (d *Data) WithErr(err error) {
	if err != nil {
		d.Message(err.Error())
		d.Error()
	} else {
		d.Success()
	}
}

func (d *Data) WithErrData(data interface{}, err error) {

	if data != nil {
		d.Data(data)
	}

	if err != nil {
		d.Message(err.Error())
		d.Error()
	} else {
		d.Success()
	}
}

// 分隔线

func ResponseBase(c *gin.Context, code int, message string, data interface{}) {
	var h = gin.H{}

	h["code"] = code
	h["data"] = data
	h["msg"] = message
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"data": data,
		"msg":  message,
	})
}

func Success(c *gin.Context) {
	ResponseBase(c, SUCCESS, "操作成功", map[string]interface{}{})
}

func SuccessWithMessage(c *gin.Context, message string) {
	ResponseBase(c, SUCCESS, message, map[string]interface{}{})
}

func SuccessWithData(c *gin.Context, data interface{}) {
	ResponseBase(c, SUCCESS, "操作成功", data)
}

func SuccessWithDetail(c *gin.Context, message string, data interface{}) {
	ResponseBase(c, SUCCESS, message, data)
}

func Error(c *gin.Context) {
	ResponseBase(c, 400, "操作失败", map[string]interface{}{})
}

func ErrorWithMessage(c *gin.Context, messages string) {
	ResponseBase(c, 400, messages, map[string]interface{}{})
}
